<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>商品放大镜效果</title>
    <style>
        .box {
            width: 350px;
            height: 350px;
            margin: 100px;
            border: 1px solid #ccc;
            position: relative;
        }

        img {
            vertical-align: top;
        }

        .big {
            width: 450px;
            height: 450px;
            position: absolute;
            top: 0;
            left: 360px;
            border: 1px solid #ccc;
            overflow: hidden;
            display: none;
        }

        .big img {
            position: absolute;
            top: 0;
            left: 0;
        }

        .small {
            position: relative;
        }

        .mask {
            width: 100px;
            height: 100px;
            background: rgba(0, 0, 0, 0.4);
            position: absolute;
            top: 0;
            left: 0;
            cursor: move;
            display: none;
        }
    </style>
</head>
<body>
<div class="box">
    <div class="small">
        <img src="001.jpg" alt="">
        <div class="mask"></div>
    </div>

    <div class="big">
        <img src="0001.jpg">
    </div>
</div>
</body>
</html>

<script>
    window.onload = function () {
        var box = document.getElementsByClassName("box")[0];
        var small = box.children[0];
        var big = box.children[1];
        var mask = small.children[1];
        var bigImage = big.children[0];

        small.onmouseover = function () {
            mask.style.display = "block";
            big.style.display = "block";
        }

        small.onmouseout = function () {
            mask.style.display = "none";
            big.style.display = "none";
        }

        var x = 0;
        var y = 0;

        small.onmousemove = function (event) {
            var event = event || window.event;

            x = event.clientX - this.offsetParent.offsetLeft - mask.offsetWidth / 2;
            y = event.clientY - this.offsetParent.offsetTop - mask.offsetHeight / 2;

            if (x < 0) {
                x = 0;
            } else if (x > this.offsetWidth - mask.offsetWidth) {
                x = this.offsetWidth - mask.offsetWidth
            }
            if (y < 0) {
                y = 0;
            } else if (y > this.offsetHeight - mask.offsetHeight) {
                y = this.offsetHeight - mask.offsetHeight;
            }
            mask.style.left = x + "px";
            mask.style.top = y + "px";
            bigImage.style.left = -x * big.offsetWidth / small.offsetWidth + "px";
            bigImage.style.top = -y * big.offsetHeight / small.offsetHeight + "px";
        }
    }
</script>